import { Table, Tree, Modal, Form, Input, message, Space, Typography, Button } from 'antd'
import React, { useState, useEffect, useRef, useImperativeHandle } from'react'
import { getTypeTree, insertTypeTree, updateTypeTree, deleteTypeTree } from '@/api/type-tree.js'
import { cloneDeep } from 'lodash'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons'
import './index.less'

const { Text } = Typography;

export const getTreeIdList = (treeData) => {
  const treeIdList = []
  treeData = treeData || []
  treeData.forEach(item => {
    treeIdList.push(item.id)
    if (item.children) {
      treeIdList.push(...getTreeIdList(item.children))
    }
  })
  return treeIdList
}

const TypeTree = React.forwardRef((props, ref) => {
  const { typeCode, onSelect, onRightClick } = props
  const treeMap = {}

  const fieldNames = {
    title: 'name',
    key: 'id',
    children: 'children'
  }

  const [treeData, setTreeData] = useState([])

  const [defaultSelectedKeys, setDefaultSelectedKeys] = useState([])
  const [ expandedKeys, setExpandedKeys ] = useState([])

  const requestTreeData = (setSelect) => {
    getTypeTree({typeCode}).then(res => {
      setTreeData(res.data || [])
      setExpandedKeys(getTreeIdList(res.data))

      if (setSelect && res.data.length > 0) {
        setDefaultSelectedKeys([res.data[0].id])
        onSelect(res.data[0])
      }
    })
  }

  useEffect(() => {
    requestTreeData(true)
  }, [])

  useImperativeHandle(
    ref,
    () => ({
      addTopLevel() {
        onAdd()
      }
    }),
    []
  )

  const formRef = useRef()
  
  const [modalData, setModalData] = useState({
    visible: false,
    confirmLoading: false,
    parentData: null,
    formData: null,
    rules: {
      typeName: [
        { required: true, message: '请输入分类名称' }
      ]
    }
  })

  const [form] = Form.useForm()

  const setInitValue = (data) => {
    form.setFieldsValue({
      typeName: data.name || ''
    })
  }

  const onAdd = (parentData) => {
    setModalData({
      ...modalData,
      parentData,
      formData: {
        typeCode,
        typeName: ''
      },
      visible: true
    })

    setInitValue({})
  }

  const onEdit = (data) => {
    setModalData({
      ...modalData,
      parentData: treeMap[data.parent_id],
      formData: data,
      visible: true
    })
    setInitValue(data)
  }

  const onDelete = (data) => {
    deleteTypeTree(data).then(() => {
      message.success('删除成功')
      requestTreeData(true)
    })
  }

  const onTreeSelect = (selectedKeys, info) => {
    if (info.selectedNodes.length > 0) {
      onSelect(info.selectedNodes[0])
    }
  }

  const onOk = () => {
    formRef.current.validateFields()
      .then((value) => {
        const submitData = cloneDeep(value)
        let menthod = insertTypeTree
        if (modalData.formData.id) {
          menthod = updateTypeTree
        } else {
          submitData.typeSupId = modalData.parentData ? modalData.parentData.id : '0'
        }
        setModalData({
          ...modalData,
          confirmLoading: true
        })
        menthod({...modalData.formData, ...submitData}).then(() => {
          requestTreeData()
          message.success('保存成功')
          setModalData({
            ...modalData,
            visible: false,
            confirmLoading: false
          })
        })
      })
  }

  const onCancel = () => {
    setModalData({
      ...modalData,
      visible: false
    })
  }

  const titleRender = (node) => {
    treeMap[node.id] = node
    return <div className='flex-row'>
      <Text className='flex-1' ellipsis={true}>
        {node.name}
      </Text>
      <Space className='flex-shrink' size={6}>
        {/* <Button className='icon-btn' type='text' size="small" title='添加子分类' icon={<PlusOutlined />} onClick={() => onAdd(node)}/> */}
        <Button className='icon-btn' type='text' size="small" title='编辑分类' icon={<EditOutlined />} onClick={() => onEdit(node)}/>
        <Button className='icon-btn' type='text' size="small" title='删除分类' icon={<DeleteOutlined />} onClick={() => onDelete(node)}/>
      </Space>
    </div>
  }

  const columns = [
    {
      title: '序号',
      width: '50px',
      dataIndex: 'id',
      render(key, recrod, index) {
        return index + 1
      }
    },
    {
      title: '分类',
      dataIndex: 'name',
      render(key, record) {
        return <div className='category-name'>{key}</div>
      }
    },
    {
      title: '',
      dataIndex: 'key',
      width: '66px',
      render: (key, record, index) => {
        return (
          <Space>
            <Button
              className="icon-btn"
              type='text'
              icon={<EditOutlined />}
              size="small"
              onClick={() => onEdit(record)}
            />
            <Button
              type='text'
              className="icon-btn"
              icon={<DeleteOutlined />}
              size="small"
              onClick={() => onDelete(record)}
            />
          </Space>
        )
      },
    }
  ]

  const containerRef = useRef()
  const [scroll, setScroll] = useState(false)

  useEffect(() => {
    if (containerRef.current) {
      let y = containerRef.current.clientHeight - 50
      y = treeData.length * 48 < y ? false : y
      setScroll(y ? { y } : null)
    }
  }, [containerRef, treeData])

  const onRow = (record) => {
    return {
      onClick: (event) => {
        onSelect(record)
      },
    };
  }

  return <>
    <div ref={containerRef} style={{height: '100%'}}>
      <Table
        rowKey="id"
        onRow={onRow}
        scroll={scroll}
        columns={columns}
        dataSource={treeData}
        pagination={false}
      ></Table>
      {/* <Tree expandedKeys={expandedKeys} defaultSelectedKeys={defaultSelectedKeys} fieldNames={fieldNames}  blockNode={true} treeData={treeData} defaultExpandAll titleRender={titleRender} onSelect={onTreeSelect} onRightClick={onRightClick}/> */}
      <Modal title="新增分类" centered confirmLoading={modalData.confirmLoading} open={modalData.visible} onOk={onOk} onCancel={onCancel}>
        <Form ref={formRef} form={form} layout="vertical" initialValues={modalData.formData}>
          {/* <Form.Item label="上级分类">
            <Input value={modalData.parentData ? modalData.parentData.name : '一级分类'} placeholder="上级分类" autoComplete='off'/>
          </Form.Item> */}
          <Form.Item label="分类名称" name="typeName" rules={modalData.rules.typeName}>
            <Input placeholder="请输入分类名称" autoComplete='off'/>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  </> 
})

TypeTree.displayName = 'TypeTree'

export default TypeTree;